define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'echarts'], function ($, undefined, Backend, Table, Form, echarts) {
    
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'scanwork/production_plan/index' + location.search,
                    add_url: 'scanwork/production_plan/add',
                    edit_url: 'scanwork/production_plan/edit',
                    del_url: 'scanwork/production_plan/del',
                    multi_url: 'scanwork/production_plan/multi',
                    table: 'production_plan',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},
                        {field: 'plan_code', title: __('计划编码'), operate: 'LIKE'},
                        {field: 'order_id', title: __('关联订单'), operate: 'LIKE'},
                        {field: 'product_name', title: __('产品名称'), operate: 'LIKE'},
                        {field: 'product_model', title: __('产品型号'), operate: 'LIKE'},
                        {field: 'total_quantity', title: __('计划数量'), align: 'center'},
                        {field: 'actual_quantity', title: __('实际数量'), align: 'center'},
                        {field: 'planned_start_time', title: __('计划开始时间'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'planned_end_time', title: __('计划结束时间'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'status', title: __('状态'), searchList: {"0":__('草稿'),"1":__('已审核'),"2":__('进行中'),"3":__('已完成'),"4":__('已取消')}, formatter: function(value, row, index) {
                            var statusMap = {
                                '0': {text: '草稿', class: 'label-default'},
                                '1': {text: '已审核', class: 'label-info'},
                                '2': {text: '进行中', class: 'label-warning'},
                                '3': {text: '已完成', class: 'label-success'},
                                '4': {text: '已取消', class: 'label-danger'}
                            };
                            var status = statusMap[value] || {text: value, class: 'label-default'};
                            return '<span class="label ' + status.class + '">' + status.text + '</span>';
                        }},
                        {field: 'createtime', title: __('创建时间'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('操作'), table: table, events: {
                            'click .btn-allocate': function (e, value, row, index) {
                                Fast.api.open('scanwork/production_plan/allocate/ids/' + row.id, '分配工序', {
                                    area: ['90%', '90%']
                                });
                                return false;
                            },
                            'click .btn-allocations': function (e, value, row, index) {
                                Fast.api.open('scanwork/production_plan/allocations/ids/' + row.id, '查看分工', {
                                    area: ['90%', '90%']
                                });
                                return false;
                            },
                            'click .btn-progressstats': function (e, value, row, index) {
                                Fast.api.open('scanwork/production_plan/progressstats/ids/' + row.id, '进度统计', {
                                    area: ['90%', '90%']
                                });
                                return false;
                            },
                            'click .btn-progress': function (e, value, row, index) {
                                Fast.api.open('scanwork/production_plan/progress/ids/' + row.id, '生产进度', {
                                    area: ['90%', '90%']
                                });
                                return false;
                            }
                        }, formatter: function (value, row, index) {
                            var html = '';
                            if (row.id) {
                                html += '<a href="javascript:;" class="btn btn-xs btn-success btn-allocate" data-id="' + row.id + '"><i class="fa fa-tasks"></i> 分配工序</a> ';
                                html += '<a href="javascript:;" class="btn btn-xs btn-info btn-allocations" data-id="' + row.id + '"><i class="fa fa-list"></i> 查看分工</a> ';
                                html += '<a href="javascript:;" class="btn btn-xs btn-warning btn-progressstats" data-id="' + row.id + '"><i class="fa fa-chart-bar"></i> 进度统计</a> ';
                                html += '<a href="javascript:;" class="btn btn-xs btn-primary btn-progress" data-id="' + row.id + '"><i class="fa fa-chart-line"></i> 生产进度</a> ';
                                html += Table.api.formatter.operate.call(this, value, row, index);
                            } else {
                                html += '<span class="text-muted">无操作</span>';
                            }
                            return html;
                        }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        progress: function () {
            Controller.api.bindevent();
        },
        allocate: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                
                // 存储订单产品数据
                var orderProductsData = {};
                
                // 订单选择变化时，加载对应的产品
                $('#c-order_id').on('change', function() {
                    var orderId = $(this).val();
                    var productSelect = $('#c-product_name');
                    var modelSelect = $('#c-product_model');
                    
                    // 清空产品和型号选择
                    productSelect.empty().append('<option value="">请选择产品</option>');
                    modelSelect.empty().append('<option value="">请选择型号</option>');
                    
                    if (orderId) {
                        // 获取订单的产品信息
                        $.get('scanwork/production_plan/getOrderProducts', {order_id: orderId}, function(data) {
                            if (data.code === 1) {
                                var products = data.data;
                                var productOptions = '<option value="">请选择产品</option>';
                                
                                // 去重产品并存储完整数据
                                var uniqueProducts = {};
                                orderProductsData = {};
                                
                                products.forEach(function(item) {
                                    if (!uniqueProducts[item.product_id]) {
                                        uniqueProducts[item.product_id] = item.product_name;
                                        productOptions += '<option value="' + item.product_name + '" data-product-id="' + item.product_id + '">' + item.product_name + '</option>';
                                        
                                        // 存储该产品的所有型号数据
                                        orderProductsData[item.product_id] = [];
                                    }
                                    
                                    // 将型号数据存储到对应产品下
                                    orderProductsData[item.product_id].push({
                                        model_id: item.model_id,
                                        model_name: item.model_name,
                                        quantity: item.quantity
                                    });
                                });
                                
                                productSelect.html(productOptions);
                                
                                // 刷新selectpicker
                                productSelect.selectpicker('refresh');
                                modelSelect.selectpicker('refresh');
                            }
                        });
                    }
                });
                
                // 产品选择变化时，加载对应的型号
                $('#c-product_name').on('change', function() {
                    var productId = $(this).find('option:selected').data('product-id');
                    var modelSelect = $('#c-product_model');
                    
                    // 清空型号选择
                    modelSelect.empty().append('<option value="">请选择型号</option>');
                    
                    if (productId && orderProductsData[productId]) {
                        var modelOptions = '<option value="">请选择型号</option>';
                        var uniqueModels = {};
                        
                        // 去重型号
                        orderProductsData[productId].forEach(function(item) {
                            if (!uniqueModels[item.model_id]) {
                                uniqueModels[item.model_id] = item.model_name;
                                modelOptions += '<option value="' + item.model_name + '" data-model-id="' + item.model_id + '" data-quantity="' + item.quantity + '">' + item.model_name + ' (数量: ' + item.quantity + ')</option>';
                            }
                        });
                        
                        modelSelect.html(modelOptions);
                        
                        // 刷新selectpicker
                        modelSelect.selectpicker('refresh');
                    }
                });
                
                // 型号选择变化时，设置最大数量限制并生成计划名称
                $('#c-product_model').on('change', function() {
                    var selectedOption = $(this).find('option:selected');
                    var maxQuantity = selectedOption.data('quantity');
                    var quantityInput = $('#c-planned_quantity');
                    var planNameInput = $('#c-plan_name');
                    
                    if (maxQuantity) {
                        // 设置最大数量属性
                        quantityInput.attr('max', maxQuantity);
                        quantityInput.attr('data-rule', 'required;number;max[' + maxQuantity + ']');
                        
                        // 添加提示信息
                        var helpText = '最大数量: ' + maxQuantity;
                        var helpElement = quantityInput.siblings('.help-block');
                        if (helpElement.length === 0) {
                            helpElement = $('<div class="help-block"></div>');
                            quantityInput.after(helpElement);
                        }
                        helpElement.text(helpText);
                    } else {
                        // 清除限制
                        quantityInput.removeAttr('max');
                        quantityInput.attr('data-rule', 'required;number');
                        quantityInput.siblings('.help-block').remove();
                    }
                    
                    // 自动生成计划名称
                    var productName = $('#c-product_name').val();
                    var modelName = $(this).val();
                    if (productName && modelName) {
                        var planName = productName + ' - ' + modelName + ' - 生产计划';
                        planNameInput.val(planName);
                    }
                });
                
                // 分配工序功能
                if ($('.allocate-process').length > 0) {
                    var planId = $('#plan-id').val();
                    var totalQuantity = parseInt($('#total-quantity').val()) || 0;
                    var currentProcess = null;
                    
                    // 获取工人列表 - 从隐藏的select中获取
                    var userList = {};
                    $('#hidden-user-list option').each(function() {
                        var value = $(this).val();
                        var text = $(this).text();
                        if (value) {
                            userList[value] = text;
                        }
                    });
                    
                    // 分配按钮点击事件
                    $(document).on('click', '.allocate-process', function() {
                        currentProcess = {
                            id: $(this).data('process-id'),
                            name: $(this).data('process-name'),
                            remainingQuantity: $(this).data('remaining-quantity')
                        };
                        
                        // 显示分配表单
                        generateAllocationForm([currentProcess]);
                        $('#current-process-name').text(currentProcess.name);
                        $('#allocation-form').show();
                    });
                    
                    // 生成分配表单
                    function generateAllocationForm(processes) {
                        var html = '';
                        processes.forEach(function(process, index) {
                            var userOptions = '<option value="">请选择工人</option>';
                            for (var userId in userList) {
                                userOptions += '<option value="' + userId + '">' + userList[userId] + '</option>';
                            }
                            
                            html += '<div class="panel panel-default allocation-item" data-process-id="' + process.id + '">' +
                                '<div class="panel-heading">' +
                                    '<h5 class="panel-title">' + process.name + ' - 剩余数量：' + process.remainingQuantity + '</h5>' +
                                '</div>' +
                                '<div class="panel-body">' +
                                    '<div class="row">' +
                                        '<div class="col-md-6">' +
                                            '<label>分配工人：</label>' +
                                            '<select class="form-control worker-select" name="allocations[' + index + '][user_id]" required>' +
                                                userOptions +
                                            '</select>' +
                                        '</div>' +
                                        '<div class="col-md-4">' +
                                            '<label>分配数量：</label>' +
                                            '<input type="number" class="form-control quantity-input" name="allocations[' + index + '][quantity]" min="1" max="' + process.remainingQuantity + '" required>' +
                                        '</div>' +
                                        '<div class="col-md-2">' +
                                            '<label>&nbsp;</label>' +
                                            '<button type="button" class="btn btn-danger btn-sm remove-allocation" data-process-id="' + process.id + '">删除</button>' +
                                        '</div>' +
                                    '</div>' +
                                    '<input type="hidden" name="allocations[' + index + '][process_id]" value="' + process.id + '">' +
                                '</div>' +
                            '</div>';
                        });
                        
                        $('#allocation-form-content').html(html);
                    }
                    
                    // 加载工人选项
                    function loadWorkerOptions() {
                        var workerOptions = '<option value="">请选择工人</option>';
                        
                        // 从隐藏的select中获取工人列表
                        $('#hidden-user-list option').each(function() {
                            var value = $(this).val();
                            var text = $(this).text();
                            if (value) {
                                workerOptions += '<option value="' + value + '">' + text + '</option>';
                            }
                        });
                        
                        $('.worker-select').html(workerOptions);
                    }
                    
                    // 删除分配项
                    $(document).on('click', '.remove-allocation', function() {
                        $('.allocation-item').remove();
                        $('#allocation-form').hide();
                    });
                    
                    // 取消分配
                    $('#cancel-allocation').click(function() {
                        $('#allocation-form').hide();
                    });
                    
                    // 保存分配
                    $('#save-allocations').click(function() {
                        var allocations = [];
                        
                        // 收集分配数据
                        $('.allocation-item').each(function() {
                            var processId = $(this).data('process-id');
                            var userId = $(this).find('.worker-select').val();
                            var quantity = parseInt($(this).find('.quantity-input').val()) || 0;
                            
                            if (userId && quantity > 0) {
                                allocations.push({
                                    process_id: processId,
                                    user_id: userId,
                                    quantity: quantity
                                });
                            }
                        });
                        
                        if (allocations.length === 0) {
                            alert('请至少完成一个分配！');
                            return;
                        }
                        
                        // 提交数据
                        $.post('scanwork/production_plan/saveBatchAllocate', {
                            plan_id: planId,
                            allocations: allocations
                        }, function(result) {
                            if (result.code === 1) {
                                alert('分配保存成功！');
                                // 关闭弹窗并刷新父页面
                                if (parent && parent.Fast && parent.Fast.api && parent.Fast.api.close) {
                                    try {
                                        parent.Fast.api.close();
                                    } catch (e) {
                                        console.log('关闭弹窗失败，直接刷新页面');
                                    }
                                    parent.location.reload();
                                } else {
                                    location.reload();
                                }
                            } else {
                                alert('保存失败：' + result.msg);
                            }
                        }, 'json');
                    });
                }
            }
        },
        
        progress: function () {
            // 初始化图表
            Controller.initCharts();
            
            // 绑定详情按钮事件
            Controller.bindDetailEvents();
        },
        
        initCharts: function () {
            
            // 1. 完成率环形图
            var completionChart = echarts.init(document.getElementById('completionChart'));
            var completionRate = parseInt($('#completion-rate').data('rate')) || 0;
            var remainingRate = 100 - completionRate;
            var completionOption = {
                series: [{
                    type: 'pie',
                    radius: ['60%', '80%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '20',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        {value: completionRate, name: '已完成', itemStyle: {color: '#4CAF50'}},
                        {value: remainingRate, name: '未完成', itemStyle: {color: '#E0E0E0'}}
                    ]
                }]
            };
            completionChart.setOption(completionOption);

            // 2. 整体进度柱状图
            var overallChart = echarts.init(document.getElementById('overallProgressChart'));
            var totalQuantity = parseInt($('#total-quantity').data('value')) || 0;
            var completedQuantity = parseInt($('#completed-quantity').data('value')) || 0;
            var remainingQuantity = totalQuantity - completedQuantity;
            var overallOption = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [{
                    type: 'category',
                    data: ['总数量', '已完成', '剩余'],
                    axisTick: {
                        alignWithLabel: true
                    }
                }],
                yAxis: [{
                    type: 'value'
                }],
                series: [{
                    name: '数量',
                    type: 'bar',
                    barWidth: '60%',
                    data: [
                        {value: totalQuantity, itemStyle: {color: '#2196F3'}},
                        {value: completedQuantity, itemStyle: {color: '#4CAF50'}},
                        {value: remainingQuantity, itemStyle: {color: '#FF9800'}}
                    ]
                }]
            };
            overallChart.setOption(overallOption);

            // 3. 工序完成率饼图
            var processChart = echarts.init(document.getElementById('processPieChart'));
            var processData = [];
            $('.process-data').each(function() {
                var name = $(this).data('name');
                var rate = parseInt($(this).data('rate')) || 0;
                processData.push({
                    value: rate,
                    name: name
                });
            });
            
            var processOption = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c}% ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [{
                    name: '完成率',
                    type: 'pie',
                    radius: '50%',
                    data: processData,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            };
            processChart.setOption(processOption);

            // 4. 员工完成率排行
            var employeeChart = echarts.init(document.getElementById('employeeRankingChart'));
            var employeeLabels = [];
            var employeeData = [];
            
            $('.employee-data').each(function() {
                employeeLabels.push($(this).data('name'));
                employeeData.push(parseInt($(this).data('rate')) || 0);
            });
            
            var employeeOption = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    boundaryGap: [0, 0.01]
                },
                yAxis: {
                    type: 'category',
                    data: employeeLabels
                },
                series: [{
                    name: '完成率',
                    type: 'bar',
                    data: employeeData,
                    itemStyle: {
                        color: '#4CAF50'
                    }
                }]
            };
            employeeChart.setOption(employeeOption);

            // 5. 订单进度对比
            var orderChart = echarts.init(document.getElementById('orderProgressChart'));
            var orderLabels = [];
            var orderData = [];
            
            $('.order-data').each(function() {
                orderLabels.push($(this).data('name'));
                orderData.push(parseInt($(this).data('rate')) || 0);
            });
            
            var orderOption = {
                tooltip: {
                    trigger: 'axis'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: orderLabels
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    name: '完成率',
                    type: 'line',
                    stack: 'Total',
                    data: orderData,
                    smooth: true,
                    lineStyle: {
                        color: '#2196F3'
                    },
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0, color: 'rgba(33, 150, 243, 0.3)'
                            }, {
                                offset: 1, color: 'rgba(33, 150, 243, 0.1)'
                            }]
                        }
                    }
                }]
            };
            orderChart.setOption(orderOption);

            // 响应式处理
            window.addEventListener('resize', function() {
                completionChart.resize();
                overallChart.resize();
                processChart.resize();
                employeeChart.resize();
                orderChart.resize();
            });
        },

        // 绑定详情按钮事件
        bindDetailEvents: function() {
            $(document).on('click', '[data-action]', function(e) {
                e.preventDefault();
                var action = $(this).data('action');
                var $btn = $(this);
                
                switch(action) {
                    case 'showOrderDetails':
                        var orderId = $btn.data('order-id');
                        Controller.showOrderDetails(orderId);
                        break;
                    case 'showProductDetails':
                        var productId = $btn.data('product-id');
                        Controller.showProductDetails(productId);
                        break;
                    case 'showProcessDetails':
                        var processName = $btn.data('process-name');
                        Controller.showProcessDetails(processName);
                        break;
                    case 'showEmployeeDetails':
                        var userId = $btn.data('user-id');
                        Controller.showEmployeeDetails(userId);
                        break;
                    case 'showModelProcesses':
                        var modelName = $btn.data('model-name');
                        var processes = $btn.data('processes');
                        Controller.showModelProcesses(modelName, processes);
                        break;
                }
            });
        },

        // 详情相关方法
        showOrderDetails: function(orderId) {
            $('#detailModalTitle').text('订单详情');
            $('#detailModalBody').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> 加载中...</div>');
            $('#detailModal').modal('show');
            
            // 通过AJAX获取订单详情
            $.get('scanwork/production_plan/getOrderDetails', {order_id: orderId})
                .done(function(response) {
                    if (response.code === 1) {
                        var data = response.data;
                        var html = '<div class="order-details">';
                        html += '<h5><i class="fa fa-file-text"></i> 订单信息</h5>';
                        html += '<div class="row">';
                        html += '<div class="col-md-6"><strong>订单名称：</strong>' + data.order.order_name + '</div>';
                        html += '<div class="col-md-6"><strong>订单编号：</strong>' + data.order.order_no + '</div>';
                        html += '</div>';
                        html += '<h5><i class="fa fa-list"></i> 生产计划详情</h5>';
                        html += '<div class="table-responsive">';
                        html += '<table class="table table-bordered table-striped">';
                        html += '<thead><tr><th>计划编号</th><th>产品名称</th><th>型号</th><th>总数量</th><th>工序分配</th></tr></thead>';
                        html += '<tbody>';
                        
                        data.plans.forEach(function(plan) {
                            html += '<tr>';
                            html += '<td>' + plan.plan_code + '</td>';
                            html += '<td>' + plan.product_name + '</td>';
                            html += '<td>' + plan.product_model + '</td>';
                            html += '<td>' + plan.total_quantity + '</td>';
                            html += '<td><button class="btn btn-xs btn-info" onclick="Controller.showPlanAllocations(' + plan.plan_id + ')">查看分配</button></td>';
                            html += '</tr>';
                        });
                        
                        html += '</tbody></table></div>';
                        html += '<div id="allocationDetails"></div>';
                        html += '</div>';
                        
                        $('#detailModalBody').html(html);
                    } else {
                        $('#detailModalBody').html('<div class="alert alert-danger">' + response.msg + '</div>');
                    }
                })
                .fail(function() {
                    $('#detailModalBody').html('<div class="alert alert-danger">获取订单详情失败</div>');
                });
        },

        showProcessDetails: function(processName) {
            $('#detailModalTitle').text('工序详情 - ' + processName);
            $('#detailModalBody').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> 加载中...</div>');
            $('#detailModal').modal('show');
            
            // 通过AJAX获取工序详情
            $.get('scanwork/production_plan/getProcessDetails', {process_name: processName})
                .done(function(response) {
                    if (response.code === 1) {
                        var data = response.data;
                        var html = '<div class="process-details">';
                        html += '<h5><i class="fa fa-cogs"></i> 工序信息</h5>';
                        html += '<div class="row">';
                        html += '<div class="col-md-6"><strong>工序名称：</strong>' + data.process.name + '</div>';
                        html += '<div class="col-md-6"><strong>工序描述：</strong>' + (data.process.description || '无') + '</div>';
                        html += '</div>';
                        html += '<h5><i class="fa fa-list"></i> 分配记录</h5>';
                        html += '<div class="table-responsive">';
                        html += '<table class="table table-bordered table-striped">';
                        html += '<thead><tr><th>订单</th><th>产品</th><th>型号</th><th>员工</th><th>分配数量</th><th>已完成</th><th>完成率</th><th>状态</th></tr></thead>';
                        html += '<tbody>';
                        
                        data.allocations.forEach(function(allocation) {
                            var statusClass = allocation.completion_rate === 100 ? 'label-success' : 
                                             allocation.completion_rate > 0 ? 'label-warning' : 'label-default';
                            html += '<tr>';
                            html += '<td>' + allocation.order_name + '</td>';
                            html += '<td>' + allocation.product_name + '</td>';
                            html += '<td>' + allocation.model_name + '</td>';
                            html += '<td>' + allocation.employee_name + '</td>';
                            html += '<td>' + allocation.allocated_quantity + '</td>';
                            html += '<td>' + allocation.completed_quantity + '</td>';
                            html += '<td><span class="label ' + statusClass + '">' + allocation.completion_rate + '%</span></td>';
                            html += '<td><span class="label label-info">' + allocation.status + '</span></td>';
                            html += '</tr>';
                        });
                        
                        html += '</tbody></table></div>';
                        html += '</div>';
                        
                        $('#detailModalBody').html(html);
                    } else {
                        $('#detailModalBody').html('<div class="alert alert-danger">' + response.msg + '</div>');
                    }
                })
                .fail(function() {
                    $('#detailModalBody').html('<div class="alert alert-danger">获取工序详情失败</div>');
                });
        },

        showProductDetails: function(productId) {
            $('#detailModalTitle').text('产品详情');
            $('#detailModalBody').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> 加载中...</div>');
            $('#detailModal').modal('show');
            
            // 通过AJAX获取产品详情
            $.get('scanwork/production_plan/getProductDetails', {product_id: productId})
                .done(function(response) {
                    if (response.code === 1) {
                        var data = response.data;
                        var html = '<div class="product-details">';
                        html += '<h5><i class="fa fa-cube"></i> 产品信息</h5>';
                        html += '<div class="row">';
                        html += '<div class="col-md-6"><strong>产品名称：</strong>' + data.product.name + '</div>';
                        html += '<div class="col-md-6"><strong>产品编码：</strong>' + (data.product.code || '无') + '</div>';
                        html += '</div>';
                        html += '<h5><i class="fa fa-list"></i> 型号进度</h5>';
                        html += '<div class="table-responsive">';
                        html += '<table class="table table-bordered table-striped">';
                        html += '<thead><tr><th>型号名称</th><th>总数量</th><th>已完成</th><th>完成率</th><th>工序详情</th></tr></thead>';
                        html += '<tbody>';
                        
                        data.models.forEach(function(model) {
                            var statusClass = model.completion_rate === 100 ? 'label-success' : 
                                             model.completion_rate > 0 ? 'label-warning' : 'label-default';
                            html += '<tr>';
                            html += '<td>' + model.model_name + '</td>';
                            html += '<td>' + model.total_quantity + '</td>';
                            html += '<td>' + model.completed_quantity + '</td>';
                            html += '<td><span class="label ' + statusClass + '">' + model.completion_rate + '%</span></td>';
                            html += '<td><button class="btn btn-xs btn-info" data-action="showModelProcesses" data-model-name="' + model.model_name + '" data-processes=\'' + JSON.stringify(model.processes) + '\'>查看工序</button></td>';
                            html += '</tr>';
                        });
                        
                        html += '</tbody></table></div>';
                        html += '<h5><i class="fa fa-cogs"></i> 工序进度详情</h5>';
                        html += '<div id="processDetails">点击"查看工序"按钮查看详细进度</div>';
                        html += '</div>';
                        
                        $('#detailModalBody').html(html);
                    } else {
                        $('#detailModalBody').html('<div class="alert alert-danger">' + response.msg + '</div>');
                    }
                })
                .fail(function() {
                    $('#detailModalBody').html('<div class="alert alert-danger">获取产品详情失败</div>');
                });
        },

        showModelProcesses: function(modelName, processes) {
            var html = '<div class="process-details">';
            html += '<h6><i class="fa fa-cogs"></i> ' + modelName + ' - 工序进度</h6>';
            html += '<div class="table-responsive">';
            html += '<table class="table table-bordered table-striped table-sm">';
            html += '<thead><tr><th>工序名称</th><th>分配数量</th><th>已完成</th><th>完成率</th><th>状态</th></tr></thead>';
            html += '<tbody>';
            
            if (processes && processes.length > 0) {
                processes.forEach(function(process) {
                    var statusClass = process.completion_rate === 100 ? 'label-success' : 
                                     process.completion_rate > 0 ? 'label-warning' : 'label-default';
                    var statusText = process.completion_rate === 100 ? '已完成' : 
                                    process.completion_rate > 0 ? '进行中' : '待开始';
                    html += '<tr>';
                    html += '<td>' + process.process_name + '</td>';
                    html += '<td>' + process.allocated_quantity + '</td>';
                    html += '<td>' + process.completed_quantity + '</td>';
                    html += '<td><span class="label ' + statusClass + '">' + process.completion_rate + '%</span></td>';
                    html += '<td><span class="label label-info">' + statusText + '</span></td>';
                    html += '</tr>';
                });
            } else {
                html += '<tr><td colspan="5" class="text-center text-muted">暂无工序数据</td></tr>';
            }
            
            html += '</tbody></table></div></div>';
            $('#processDetails').html(html);
        },

        showEmployeeDetails: function(userId) {
            $('#detailModalTitle').text('员工详情');
            $('#detailModalBody').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> 加载中...</div>');
            $('#detailModal').modal('show');
            
            // 通过AJAX获取员工详情
            $.get('scanwork/production_plan/getEmployeeDetails', {user_id: userId})
                .done(function(response) {
                    if (response.code === 1) {
                        var data = response.data;
                        var html = '<div class="employee-details">';
                        html += '<h5><i class="fa fa-user"></i> 员工信息</h5>';
                        html += '<div class="row">';
                        html += '<div class="col-md-6"><strong>员工姓名：</strong>' + data.user.nickname + '</div>';
                        html += '<div class="col-md-6"><strong>用户名：</strong>' + (data.user.username || '无') + '</div>';
                        html += '</div>';
                        html += '<h5><i class="fa fa-list"></i> 工作分配记录</h5>';
                        html += '<div class="table-responsive">';
                        html += '<table class="table table-bordered table-striped">';
                        html += '<thead><tr><th>订单</th><th>产品</th><th>型号</th><th>工序</th><th>分配数量</th><th>已完成</th><th>完成率</th><th>状态</th></tr></thead>';
                        html += '<tbody>';
                        
                        data.allocations.forEach(function(allocation) {
                            var statusClass = allocation.completion_rate === 100 ? 'label-success' : 
                                             allocation.completion_rate > 0 ? 'label-warning' : 'label-default';
                            html += '<tr>';
                            html += '<td>' + allocation.order_name + '</td>';
                            html += '<td>' + allocation.product_name + '</td>';
                            html += '<td>' + allocation.model_name + '</td>';
                            html += '<td>' + allocation.process_name + '</td>';
                            html += '<td>' + allocation.allocated_quantity + '</td>';
                            html += '<td>' + allocation.completed_quantity + '</td>';
                            html += '<td><span class="label ' + statusClass + '">' + allocation.completion_rate + '%</span></td>';
                            html += '<td><span class="label label-info">' + allocation.status + '</span></td>';
                            html += '</tr>';
                        });
                        
                        html += '</tbody></table></div>';
                        html += '</div>';
                        
                        $('#detailModalBody').html(html);
                    } else {
                        $('#detailModalBody').html('<div class="alert alert-danger">' + response.msg + '</div>');
                    }
                })
                .fail(function() {
                    $('#detailModalBody').html('<div class="alert alert-danger">获取员工详情失败</div>');
                });
        }
    };
    return Controller;
});
